package io.seata.samples.zk.call;

import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.exception.ZkMarshallingError;
import org.I0Itec.zkclient.serialize.ZkSerializer;
import org.apache.zookeeper.CreateMode;
import org.springframework.util.ResourceUtils;

import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * Seata 配置文件注册到 Zookeeper 中
 *
 * @author Administrator
 */
public class ZkLoadSeataConfig {
    public static void main(String[] args) {
        ZkClient zkClient = new ZkClient("127.0.0.1:2181", 6000, 2000);
        zkClient.setZkSerializer(new ZkSerializer() {
            @Override
            public byte[] serialize(Object o) throws ZkMarshallingError {
                return String.valueOf(o).getBytes(StandardCharsets.UTF_8);
            }

            @Override
            public Object deserialize(byte[] bytes) throws ZkMarshallingError {
                return new String(bytes, StandardCharsets.UTF_8);
            }
        });
        if (!zkClient.exists("/seata")) {
            zkClient.createPersistent("/seata", true);
        }
        try {
            File file = ResourceUtils.getFile("classpath:seata-config.properties");
            // 老版本seata每个配置项为一个节点
            /*Properties properties = new Properties();
            InputStream in = new FileInputStream(file);
            properties.load(in);
            Set<Object> keys = properties.keySet();
            System.out.println("配置条数：" + keys.size());
            for (Object key : keys) {
                String path = "/seata/" + key.toString();
                String value = properties.get(key).toString();
                if (!zkClient.exists(path)) {
                    zkClient.create(path, value, CreateMode.PERSISTENT);
                } else {
                    zkClient.writeData(path, value);
                }
                System.out.println(("path=" + path + ", value=" + value));
            }*/
            // 新版本seata所有配置项在一个节点中
            BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
            StringBuilder content = new StringBuilder();
            String temp = null;
            while ((temp = bufferedReader.readLine()) != null) {
                content.append(temp).append("\n");
            }
            String path = "/seata/seata.properties";
            String value = content.toString();
            if (!zkClient.exists(path)) {
                zkClient.create(path, value, CreateMode.PERSISTENT);
            } else {
                zkClient.writeData(path, value);
            }
            System.out.println(("path=" + path + ", value=" + value));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
